<template>
  <div class="bg_block">
    <headback :title="t('userDetail')">
      <template #right>
        <i @click="toShare" class="iconfont icon-linear-new-symbol-share"></i>
      </template>
    </headback>
    <div class="index_box topHead">
    <div class="content_box">
      <div class="shop_box">
        <div>
            <van-image class="shop_img" round fit="cover" v-if="shopData.avatar" :src="shopData.avatar" />
            <Blockies v-else class="border_radius" :seed="shopData.account" :size="18" :scale="2" spotcolor="#000" />
        </div>
        <div>
          <div class="star_btn" @click="goToPage('applyShop')" v-if="isSelf"> <i class="iconfont icon-ic_edit"></i> {{ t('edit') }} </div>
          <div v-else>
            <div class="star_btn" @click="starShop(false)" v-if="shopData.isCollect"> <i class="iconfont icon-ic_user-3"></i> {{ t('hasStar') }} </div>

             <div class="star_btn" @click="starShop(true)"   v-else > <i class="iconfont icon-ic_user-3"></i> {{ t('star') }} </div>
          </div>
          <div class="shop_name">{{ shopData.nickname }}</div>
          <div>{{ splitAddress(shopData.owner,9) }}</div>
          <div class="shop_describe">
            <span> {{ shopData.isCloseOut ? '可平仓' :'不可平仓' }}</span>
            <span>{{ shopData.describe }} </span> 
          </div>
        </div>
      </div>
      <van-tabs v-model:active="tabActive" shrink>
        <van-tab :title="t('orders')" v-if="nowSystem!='/c2c'">
          <div class="tab_box">
            <div class="item" :class="{ ac: active == 1 }" @click="tabChange(1)">
              {{ t('lend') }}
            </div>
            <div class="item" :class="{ ac: active == 2 }" @click="tabChange(2)">
              {{ t('borrow') }}
            </div>
            <div class="bg" :class="{ left1: active == 2 }"></div>
          </div>
          <div v-if="active == 1" class="tab_warpper">
        <van-pull-refresh v-model="refreshing1" @refresh="onRefresh1">
          <van-list
            v-model:loading="loading1"
            :immediate-check="false"
            :finished="finished1"
            :finished-text="t('noMore')"
            @load="onLoad1"
          >
            <orderItem
              v-for="item in orderList"
              :key="item.orderId"
              :data="item"
            ></orderItem>
          </van-list>
        </van-pull-refresh>
      </div>
      <div v-else-if="active == 2" class="tab_warpper">
        <van-pull-refresh v-model="refreshing2" @refresh="onRefresh2">
          <van-list
            v-model:loading="loading2"
            :immediate-check="false"
            :finished="finished2"
            :finished-text="t('noMore')"
            @load="onLoad2"
          >
            <orderItem
              v-for="item in orderList2"
              :key="item.id"
              :data="item"
            ></orderItem>
          </van-list>
        </van-pull-refresh>
      </div>
        </van-tab>

        <van-tab v-if="nowSystem!='/index'" :title="t('c2cOrder')">
          <div class="tab_box">
            <div class="item" :class="{ ac: activeC2C == 1 }" @click="tabChangeC2C(1)">
              {{ t('buy') }}
            </div>
            <div class="item" :class="{ ac: activeC2C == 2 }" @click="tabChangeC2C(2)">
              {{ t('sell') }}
            </div>
            <div class="bg" :class="{ left1: activeC2C == 2 }"></div>
          </div>
          <div v-if="activeC2C == 1" class="tab_warpper">
        <van-pull-refresh v-model="refreshing3" @refresh="onRefresh3">
          <van-list
            v-model:loading="loading3"
            :immediate-check="false"
            :finished="finished3"
            :finished-text="t('noMore')"
            @load="onLoad3"
          >
            <orderItem2
              v-for="item in orderList3"
              :key="item.orderId"
              :data="item"
              hiddenShop
            ></orderItem2>
          </van-list>
        </van-pull-refresh>
      </div>
      <div v-else-if="activeC2C == 2" class="tab_warpper">
        <van-pull-refresh v-model="refreshing4" @refresh="onRefresh4">
          <van-list
            v-model:loading="loading4"
            :immediate-check="false"
            :finished="finished4"
            :finished-text="t('noMore')"
            @load="onLoad4"
          >
            <orderItem2
              v-for="item in orderList4"
              :key="item.id"
              :data="item"
              hiddenShop
            ></orderItem2>
          </van-list>
        </van-pull-refresh>
      </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
  </div>
  <lend-u :orderType="orderType" :shopData="shopData" v-model="showlend"></lend-u>
  <borrow-u :orderType="orderType" :shopData="shopData" v-model="showborrow"></borrow-u>
  <share-user v-model="showShare" :shopInfo="shopData"></share-user>
  <videoPop v-model="showVideo"  :url="nowItem.url"></videoPop>
  <van-image-preview v-model:show="show" :startPosition="startPosition" :images="images">
    <template #image="{ src }">
      <van-image class="preview-cover" v-if="src.type == 'img'" :src="src.url" />
      <div v-if="src.type == 'video'&&show" class="preview-cover">
        <video :autoplay="true" poster="../../assets/images/black.png" muted class="video" :src="src.url" controls></video>
      </div>
    </template>
  </van-image-preview>
</template>
<script setup>
import { showToast } from "vant";
import IndexDBCache from "@/hooks/sql/useOrder.js";
const orderDB = new IndexDBCache();
import Blockies from "@/components/blockVue.vue";
import "vant/es/toast/style";
import { getJson } from "@/api/User.js";
import { useStore } from "vuex";
import { ref, reactive, onMounted, computed, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";
import { IPFS_PUBLIC_URL,nowSystem } from "@/utils/config.js";
const { locale, t } = useI18n();
import { splitAddress } from "@/utils/index.js";
import eth from "@/utils/eth.js"
import { useRouter } from "vue-router";
import loanEth from "@/utils/loanEth.js"
import userEth  from "@/utils/userEth.js"
import c2cEth from "@/utils/c2cEth.js";
const router = useRouter();
const store = useStore();
const showPopover = ref(false);
const images = ref([]);
const startPosition = ref(0);
const active = ref(1);
const activeC2C = ref(1)
const tabActive = ref(0);
const showVideo = ref(false)
const nowItem = ref({})
const show = ref(false)
const shopData = ref({
  pictureList:[]
})
const tabChange = (value) => {
  active.value = value;
  value==1?onRefresh1():onRefresh2()
};
const tabChangeC2C = (value) => {
  activeC2C.value = value;
  value==1?onRefresh3():onRefresh4()
};
const pageSize = 10
let params1 = reactive({
  page: 1,
  pageSize: pageSize,
});
let params2 = reactive({
  page: 1,
  pageSize: pageSize,
});
let params3 = reactive({
  page: 1,
  pageSize: pageSize,
});
let params4 = reactive({
  page: 1,
  pageSize: pageSize,
});
const loading1 = ref(false);
const finished1 = ref(false);
const refreshing1 = ref(false);
const loading2 = ref(false);
const finished2 = ref(false);
const refreshing2 = ref(false);
const loading3 = ref(false);
const finished3 = ref(false);
const refreshing3 = ref(false);
const loading4 = ref(false);
const finished4 = ref(false);
const refreshing4 = ref(false);
const showShare = ref(false)
const toShare = ()=>{
  showShare.value = true
}
const putImage = (list, index,item) => {
    if (item.type == 'video') {
    showVideo.value = true
    nowItem.value = item
    return
  }
  images.value = list.filter(res => res.type == 'img')
  startPosition.value = images.value.findIndex(res => res.url == item.url)
  show.value = true
};
const getShopData=async ()=>{
  if(router.currentRoute.value.query.owner){

  }else{
    showToast("No this user")
    return
  }
  shopData.value = await userEth.getUserItem(router.currentRoute.value.query.owner)
  let index = store.state.collectUser.findIndex(el => { return el.account == shopData.value.account })
  shopData.value.isCollect = index>-1
}
getShopData()
const isSelf = computed(()=>{
  return store.state.address == router.currentRoute.value.query.account || router.currentRoute.value.query.self
})
const starShop = (bool)=>{
    shopData.value.isCollect = bool
    let index = store.state.collectUser.findIndex(el => { return el.account == shopData.value.account })
    let arr = JSON.parse(JSON.stringify(store.state.collectUser)) 
    if(bool){
      if(index>-1){
        return
      }else{
        arr.push(shopData.value)
      }
    }else{
      if (index > -1) {
        arr.splice(index, 1)
      }
    }
    store.commit("changeCollectUser",arr)
}
const loading = ref(false);
const showlend = ref(false);
const showborrow = ref(false);
const orderType = ref(1);
const orderList = ref([]);
const orderList2 = ref([])
const orderList3 = ref([]);
const orderList4 = ref([])
const onRefresh1 = () => {
  // 清空列表数据
  finished1.value = false;
  refreshing1.value = true;
  params1.page = 1;
  loading1.value = true;
  try {
    onLoad1();
  } catch (err) {
    orderList.value = []
  }
};
const onRefresh2 = () => {
  // 清空列表数据
  finished2.value = false;
  refreshing2.value = true;
  params2.page = 1;
  // 重新加载数据
  // 将 loading 设置为 true，表示处于加载状态
  loading2.value = true;
  try {
    onLoad2();
  } catch (err) {
    orderList2.value = []
  }
};
const onRefresh3 = () => {
  // 清空列表数据
  finished3.value = false;
  refreshing3.value = true;
  params3.page = 1;
  loading3.value = true;
  try {
    onLoad3();
  } catch (err) {
    orderList3.value = []
  }
};
const onRefresh4 = () => {
  // 清空列表数据
  finished4.value = false;
  refreshing4.value = true;
  params4.page = 1;
  // 重新加载数据
  // 将 loading 设置为 true，表示处于加载状态
  loading4.value = true;
  try {
    onLoad4();
  } catch (err) {
    orderList4.value = []
  }
};
const onLoad1 = async () => {
  if (refreshing1.value) {
    orderList.value = []
    params1.page = 1;
    refreshing1.value = false;
  }
  try {
    loading1.value = true
    await orderDB.initDB()
    const account = router.currentRoute.value.query.owner
    let data = await orderDB.getDataByIndex('orderList', 'OrderTypeStatusOwner', ['2','0', account ], params1.page, pageSize)
    orderList.value = [...orderList.value, ...data]
    loading1.value = false
    if (data.length == pageSize) {
      params1.page = params1.page + 1
    } else {
      finished1.value = true;
    }
  } catch (err) {
    loading1.value = false;
    finished1.value = true;
  }
};
const onLoad2 = async () => {
  if (refreshing2.value) {
    orderList2.value = []
    params2.page = 1;
    refreshing2.value = false;
  }
  try {
    loading2.value = true
    await orderDB.initDB()
    const account = router.currentRoute.value.query.owner
    let data = await orderDB.getDataByIndex('orderList', 'OrderTypeStatusOwner', ['1','0', account ], params2.page, pageSize)
    orderList2.value = [...orderList2.value, ...data]
    loading2.value = false
    if (data.length == pageSize) {
      params2.page = params2.page + 1
    } else {
      finished2.value = true;
    }
  } catch (err) {
    loading2.value = false;
    finished2.value = true;
  }
};
const onLoad3 = async () => {
  if (refreshing3.value) {
    orderList3.value = []
    params3.page = 1;
    refreshing3.value = false;
  }
  try {
    loading3.value = true
    await orderDB.initDB()
    let account = router.currentRoute.value.query.owner
    if(isSelf.value){
      account = await eth.getAccount()
    }
    let data = await orderDB.getDataByIndex('c2cOrderList', 'OrderTypeStatusOwner', ['2', '0', account ], params3.page, pageSize)
    orderList3.value = [...orderList3.value, ...data]
    loading3.value = false
    if (data.length == pageSize) {
      params3.page = params3.page + 1
    } else {
      finished3.value = true;
    }
  } catch (err) {
    loading3.value = false;
    finished3.value = true;
  }
};
const onLoad4 = async () => {
  if (refreshing4.value) {
    orderList4.value = []
    params4.page = 1;
    refreshing4.value = false;
  }
  try {
    loading4.value = true
    await orderDB.initDB()
    let account = router.currentRoute.value.query.owner
    if(isSelf.value){
      account = await eth.getAccount()
    }
    let data = await orderDB.getDataByIndex('c2cOrderList', 'OrderTypeStatusOwner', ['1', '0', account ], params4.page, pageSize)
    orderList4.value = [...orderList4.value, ...data]
    loading4.value = false
    if (data.length == pageSize) {
      params4.page = params4.page + 1
    } else {
      finished4.value = true;
    }
  } catch (err) {
    loading4.value = false;
    finished4.value = true;
  }
};
const requireImg = (imgPath) => {
  return new URL(`../../assets/images/${imgPath}`, import.meta.url).href;
};
const getNewData = async () => {
  await orderDB.initDB()
  let data = await orderDB.getDataByIndex('orderList', 'OrderTypeStatusOwner', ['2','0', router.currentRoute.value.query.owner ], 1, pageSize)
  orderList.value = data

  let data2 = await orderDB.getDataByIndex('c2cOrderList', 'OrderTypeStatusOwner', ['2', '0', router.currentRoute.value.query.owner ], 1, pageSize)
  orderList3.value = data2


}
const initData = async (accounts) => {
  await onLoad1()
  await onLoad3()
  await loanEth.getTraderPendingOrders(router.currentRoute.value.query.owner)
  await c2cEth.getTraderPendingOrders(router.currentRoute.value.query.owner)
  setTimeout(()=>{
   getNewData()
  },500)
};

initData();
const goToPage = (value, type) => {
  let query = {}
  query = {
    referrer: router.currentRoute.value.query.referrer,
  };
  if(value=='applyShop'){
    query = {
      id:shopData.value.id
    }
  }
  router.push({
    name: value,
    query,
  });
};
onMounted(() => {
  ethereum.on("accountsChanged", async function (accounts) {
    initData(accounts[0]);
  });
});
</script>
<style>
:root:root {
  --van-button-primary-background: red;
  --van-pagination-item-default-color: #f39018;
  --van-pagination-disabled-opacity: #010e39 !important;
}
</style>
<style lang="scss" scoped>
:deep .van-tabs__line {
  width: 10px;
  bottom: 24px;
}
.contract_class{
  color: #ffba67;
}
.order_detail{
  display: flex;
  justify-content: space-between;
  align-items: center;
  .sum_title{
    color: #b7bdc6;
  }
  .all_sum{
      color: #f5e1bc;
    }
    .in_sum{
      color: #0ecb81;
    }
    .out_sum{
      color: #f6465d;
    }
}
.van-swipe {
    // position: absolute;
    // left: 0;
    // top: 0;
    // right: 0;
    height: 180px;

    .van-swipe-item {
      height: 250px;
      text-align: center;
      background-color: #39a9ed;

      .van-image {
        width: 10rem;
        height: 250px;
      }
    }
  }
.shop_box {
  position: relative;
  padding: 5px 0;
  margin:10px 0;
  display: flex;
  gap: 10px;
  .shop_img {
    display: flex;
    justify-content: center;
    align-items: center;
    background: #4653c8;
    border-radius: 50%;
    height: 40px;
    width: 40px;
    .default_img {
      height: 30px;
      width: 30px;
      font-size: 30px;
      display: inline-block;
      background: #010e39;
      border-radius: 8px;
      padding: 6px;
    }
  }
  .shop_name {
    font-size: 13px;
    font-weight: bold;
  }
  .shop_describe {
    font-size: 9px;
    color: #999;
    margin-top: 5px;
  }
}

.star_btn {
  height: 18px;
  padding: 0 6px;
  line-height: 18px;
  color: #fff;
  background: #f39018;
  position: absolute;
  right: 0;
  top: 5px;
  border-radius: 6px;
  font-size: 9px;
  display: flex;
  align-items: center;
  gap: 4px;
  i {
    font-size: 10px;
  }
}
.tab_box {
  margin: auto;
  position: relative;
  background: #131e3f;
  border-radius: 6px;
  display: inline-flex;
  .item {
    text-align: center;
    width: 60px;
    height: 30px;
    line-height: 30px;
    position: relative;
    z-index: 2;
    color: #c3c8d2;
  }
  .ac {
    color: #fff;
  }
  .bg {
    position: absolute;
    left: 4px;
    top: 2px;
    z-index: 1;
    width: 54px;
    height: 26px;
    background: #f39018;
    border-radius: 6px;
    transition: all 0.5s;
  }
  .left1 {
    left: 62px;
  }
}
:deep .van-pagination__item--disabled {
  background: #010e39;
}
.language_box {
  padding: 5px 0px;
  background: #222143;
  position: relative;
}
.language_item {
  font-size: 12px;
  padding: 10px 15px;
  cursor: pointer;
  text-align: center;
  display: flex;
  align-items: center;

  .van-image {
    height: 18px;
    width: 18px;
    margin-right: 8px;
  }
}
.language_item_active {
  color: rgb(246, 109, 26);
}
.status_box {
  position: relative;
  margin-top: 14px;
  .css-qmhmz {
    color: #bab9b9;
    background: #010e39;
    font-family: Rubik;
    font-weight: 400;
    font-size: 12px;
    line-height: 1.4375em;
    letter-spacing: 0.00938em;
    text-transform: none;
    display: block;
    transform-origin: left top;
    text-overflow: ellipsis;
    max-width: calc(133% - 32px);
    position: absolute;
    left: 0px;
    top: 0px;
    transform: translate(6px, -8px) scale(0.75);
    z-index: 1;
    pointer-events: auto;
    user-select: none;
    padding: 0px;
    white-space: nowrap;
    overflow: hidden;
    transition: color 200ms cubic-bezier(0, 0, 0.2, 1),
      transform 200ms cubic-bezier(0, 0, 0.2, 1),
      max-width 200ms cubic-bezier(0, 0, 0.2, 1);
  }

  display: flex;
  align-items: center;
  justify-content: center;

  .color_light {
    color: #ddd;
    display: inline-block;
    border: 1px solid #414c60;
    position: relative;
    padding: var(--van-cell-vertical-padding) 6px;
    margin-left: 10px;
    border-radius: 5px;
    display: flex;
    align-items: center;
    .icon_down {
      font-size: 10px;
      margin-left: 4px;
    }
    img {
      height: 16px;
      margin-right: 7px;
    }
  }
}
.content_box{
  padding: 16px;
}
.index_box {
  .head_box {
    margin-top: 10px;
    display: flex;
    align-items: center;
    // justify-content: space-between;
    .head_left {
      display: flex;
      align-items: center;
      .left_title {
        font-size: 26px;
        font-weight: bold;
        color: #f39018;
      }
      .icon_refresh {
        color: #c3c8d2;
        margin-left: 10px;
        font-size: 10px;
      }
    }
    .head_right_box {
      margin-left: auto;
      display: flex;
      gap: 10px;
    }
    .head_right {
      background: #f39018;
      color: #333;
      font-weight: bold;
      padding: 6px;
      border-radius: 6px;
    }
  }
  .complete_box {
    display: flex;
    align-items: center;
    margin: 5px auto;
    justify-content: center;

    .complete_sum {
      display: flex;
      margin-left: 10px;
      align-items: center;
      gap: 6px;
      img {
        height: 16px;
      }
      .sum_value {
        color: #f39018;
      }
    }
  }
  .order_list {
    .order_item {
      border: 1px solid #888;
      margin: 10px 0;
      padding: 10px 16px;
      box-sizing: border-box;
      border-radius: 10px;

      .order_content {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
      }
      .data_box {
        width: calc(50% - 5px);
        .data_name {
          font-size: 11px;
        }
        .data_value {
          font-size: 8px;
          display: flex;
          margin-top: 4px;
          align-items: center;
          gap: 3px;
          img {
            height: 12px;
          }
        }
      }
    }
  }
}
</style>
